package logic

import (
	"context"
	"fmt"
	"login/models/mysql"
	"login/pkg"

	"login/loginrpc/internal/svc"
	"login/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *loginrpc.RegisterUserRequest) (*loginrpc.RegisterUserResponse, error) {
	// todo: add your logic here and delete this line

	var userFin mysql.User
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&userFin)
	if userFin.ID != 0 {
		return nil, fmt.Errorf("用户已存在,请不要重复注册")
	}

	var user mysql.User
	user = mysql.User{
		Name:     in.Name,
		Password: pkg.Md5(in.Password),
		Email:    in.Email,
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &loginrpc.RegisterUserResponse{Id: int64(user.ID)}, nil
}
